//
//  FoundViewController.m
//  shise
//
//  Created by Darling❤️ on 14/12/17.
//  Copyright (c) 2014年 Darling❤️. All rights reserved.
//

#import "FoundViewController.h"
#import "ChangeCityViewController.h"
#import "NetHandler.h"
#import "Found.h"
#import "TwoCard.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "CrossSlipViewController.h"
#import "MoreDetailViewController.h"
#import "FoodListDetailViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "LocationViewController.h"
#import "Reachability.h"
#import "MBProgressHUD.h"

@interface FoundViewController ()<UIScrollViewDelegate>
@property(nonatomic,retain)UIScrollView *scrollView;

@property(nonatomic,retain)UIButton *buttonAction;//活动的button
@property(nonatomic,retain)UILabel *labelAction;//活动BUtton上得label
@property(nonatomic,retain)UILabel *labelCity;//城市的美食
@property(nonatomic,retain)UIButton *buttonCity;//更改城市
@property(nonatomic,retain)UIButton *buttonShop;//附近店铺的button
@property(nonatomic,retain)UIButton *buttonHot;//同城热门的button
@property(nonatomic,retain)UILabel *labelNext;//下一级的label
@property(nonatomic,retain)UIButton *buttonOne;//最后四个button,one
@property(nonatomic,retain)UIButton *buttonTwo;//最后四个button,two
@property(nonatomic,retain)UIButton *buttonThree;//最后四个button,three
@property(nonatomic,retain)UIButton *buttonFour;//最后四个button,four
@property(nonatomic,retain)UILabel *labelEnd;//结束end

@property (nonatomic,retain)UIImageView *imageV;//活动的图片
@property(nonatomic,retain)NSMutableArray *arr;
@property(nonatomic, retain)NSString *cityString;
@property(nonatomic, retain)MBProgressHUD *noHUD;

//@property(nonatomic,retain)NSMutableArray *twoCardArr;//
//@property(nonatomic,retain)NSMutableArray *eventArr;//

@end

@implementation FoundViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self handelData];
    }
    return self;
}

- (void)handelData
{
    NSString *str = @"https://api.shiseapp.com/v2/discover/?_city=%E9%A6%99%E6%B8%AF&_device=Matcha%20v2.5.0%20%28iPhone%206,%208.1.1%29&_version=2.5.0&conf_ver=1418876027&gps=38.884307,121.541181&uuid=b611c1feab43d2ee1585a574f539263f";
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSMutableDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //定义一个数组，存储解析后的数据
        NSArray *foundArr = [tempDic objectForKey:@"data"];
        //初始化这个数组
        self.arr = [NSMutableArray array];
        //遍历数组（存在字典中）
        for (NSMutableDictionary *dic in foundArr) {
            //定义个对象，把得到的值给对象赋值
            Found *found = [[Found alloc]initWithDictionary:dic];
            //转码
            found.title = [found.title stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            //把对象付给数组

            [self.arr addObject:found];
            [found release];
        }
        NSString *str = [[foundArr objectAtIndex:1]objectForKey:@"title"];
       // NSString *str1 = [[foundArr objectAtIndex:2]objectForKey:@"title"];
        
        NSLog(@"%@",str);

//        self.twoCardArr = [NSMutableArray array];
//        self.eventArr = [NSMutableArray array];
//        
//        for (NSDictionary *tempDic in foundArr) {
//            if ([[tempDic objectForKey:@"type"] isEqualToString:@"TwoCard"]) {
//                TwoCard *twocard = [[TwoCard alloc] initWithDictionary:tempDic];
//                [self.twoCardArr addObject:twocard];
//                [twocard release];
//            } else if ([[tempDic objectForKey:@"type"] isEqualToString:@"EventCard"]) {
//                Found *found = [[Found alloc] initWithDictionary:tempDic];
//                [self.eventArr addObject:found];
//                [found release];
//                
//            }
//        }
////        NSLog(@"two 数组    %@", self.twoCardArr);
//        NSLog(@"*****%@", [[[[[self.twoCardArr objectAtIndex:0] cards] objectAtIndex:0] objectForKey:@"pic"] objectForKey:@"url"]);
//
        
        
    }];
    
    //Found *found = [self.arr objectAtIndex:1];
//    [self.buttonShop setImageWithURL:[NSURL URLWithString: found.url]];

}




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
//    self.labelCity.text = @"大连";
    self.cityString = @"大连";
//    self.labelCity.text = [NSString stringWithFormat:@"%@同城美食", self.cityString];
    
    
    
    
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.scrollView = [[UIScrollView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollView];
    
    //滚动范围
    self.scrollView.contentSize = CGSizeMake(0, self.view.frame.size.height+self.view.frame.size.height/3-20);
    //置顶操作，通过点击状态栏，回到顶部
    self.scrollView.scrollsToTop = YES;
    //偏移量
    self.scrollView.contentOffset = CGPointMake(0, 0);
    //指定代理人
    self.scrollView.delegate = self;
    [_scrollView release];
    
    //***********************************//
    
    
    
//    //设置活动的button
//    //赋给图片
//    Found *found = [self.arr objectAtIndex:0];
//    NSString *str = found.url;
//    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
//    request.HTTPMethod = @"GET";
//  
//    NSURLResponse *res = nil;
//    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:nil];
//    UIImage *image = [UIImage imageWithData:data];
    
    self.buttonAction = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonAction.frame = CGRectMake(0, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height/50*12+70) ;
    //    self.buttonAction.backgroundColor = [UIColor yellowColor];
    [self.scrollView addSubview:self.buttonAction];
    [self.buttonAction setTitle:@"" forState:UIControlStateNormal];
    [self.buttonAction addTarget:self action:@selector(buttonActionClike:) forControlEvents:UIControlEventTouchUpInside];
   // [self.buttonAction setImage:image forState:UIControlStateNormal];
    [self.buttonAction setImage:[UIImage imageNamed:@"han.jpg"] forState:UIControlStateNormal];
    
    
    //设置活动button上得label
    self.labelAction = [[UILabel alloc]initWithFrame:CGRectMake(0, self.buttonAction.frame.size.height/25*4, self.buttonAction.frame.size.width, self.buttonAction.frame.size.height/2)];    self.labelAction.backgroundColor = [UIColor clearColor];
    self.labelAction.textColor = [UIColor whiteColor];
    self.labelAction.textAlignment = 1;
    //title属性的获取
    //[self.labelAction setText:@"发现------身边的美好"];
    self.labelAction.font = [UIFont boldSystemFontOfSize:25];
    
    [self.buttonAction addSubview:self.labelAction];
    [_labelAction release];

    //**********************************//
    
    
    
    
    
    
    //城市的小label
    
    Found *found1 = [self.arr objectAtIndex:1];
   // NSString *str1 = found1.title;
//    NSLog(@"--------%@",found1.title);
    
    self.labelCity = [[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.frame.size.width/100*3, self.scrollView.frame.size.height/50*13+70, self.scrollView.frame.size.width/25*12, self.scrollView.frame.size.height/200 *3)];
    self.labelCity.backgroundColor = [UIColor clearColor];
    self.labelCity.textColor = [UIColor lightGrayColor];
    self.labelCity.font = [UIFont boldSystemFontOfSize:14];
    self.labelCity.textAlignment = 0;
    self.labelCity.text = found1.title;
    [self.scrollView addSubview:self.labelCity];
    [_labelCity release];
    
    // 设定通知中心 当选中某个城市的时候将发现页面的同城美食改成相应的城市
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(receiveNotification:) name:@"changeCity" object:nil];
    // 设定通知中心 当选中某个省的时候而且这个省中只有一个元素的时候把发现页面的同城美食改为相应的省
//    NSNotificationCenter *center1 = [NSNhttp://matcha-dev.u.qiniudn.com/m_flz6-xX2VgNcMdiX.jpgotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(changeProvinceAction:) name:@"changeProvince" object:nil];
    
    //设置更改城市的button
    self.buttonCity = [UIButton buttonWithType:UIButtonTypeSystem];
    self.buttonCity = [UIButton buttonWithType:UIButtonTypeSystem];
    self.buttonCity.frame = CGRectMake(self.scrollView.frame.size.width/5*4-5, self.scrollView.frame.size.height/50*13+70, self.scrollView.frame.size.width/25*5, self.scrollView.frame.size.height/200 *3);

    self.buttonCity.backgroundColor = [UIColor clearColor];
    [self.buttonCity setTitle:@"更改城市" forState:UIControlStateNormal];
    [self.scrollView addSubview:self.buttonCity];
    [self.buttonCity addTarget:self action:@selector(buttonCityClike:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //************************************//
    
    //设置附近店铺的button
    
    
    self.buttonShop = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonShop.frame = CGRectMake(self.scrollView.frame.size.width/100*3+5-2, self.scrollView.frame.size.height/25*7+10+70, self.scrollView.frame.size.width/20*9, self.scrollView.frame.size.height/100*23);

    self.buttonShop.backgroundColor = [UIColor redColor];
    [self.scrollView addSubview:self.buttonShop];
    [self.buttonShop addTarget:self action:@selector(buttonShopClike:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonShop setImage:[UIImage imageNamed:@"near.png"] forState:UIControlStateNormal];

    
    
    
    

    
    //************************************//
    
    //设置同城热门的button
    self.buttonHot = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonHot.frame = CGRectMake(self.scrollView.frame.size.width/2+5+4, self.scrollView.frame.size.height/25*7+10+70, self.scrollView.frame.size.width/20*9, self.scrollView.frame.size.height/100*23);
    [self.scrollView addSubview:self.buttonHot];
    [self.buttonHot addTarget:self action:@selector(buttonHotClike:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonHot setImage:[UIImage imageNamed:@"hot.png"] forState:UIControlStateNormal];
    
    
    
    
    //**********************************//
    
    
    //设置下一层的lebel
    self.labelNext = [[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.frame.size.width/100*3, self.scrollView.frame.size.height/25*14+70, self.scrollView.frame.size.width, self.scrollView.frame.size.height/200*3)];
    self.labelNext.backgroundColor = [UIColor clearColor];
    self.labelNext.textColor = [UIColor lightGrayColor];
    self.labelNext.font = [UIFont boldSystemFontOfSize:14];
    self.labelNext.textAlignment = 0;
    self.labelNext.text = @"亲自下厨房";
    [self.scrollView addSubview:self.labelNext];
    [_labelNext release];
    
    //**************************************//
    
   //最后四个button,one
    self.buttonOne = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonOne.frame = CGRectMake(self.scrollView.frame.size.width/100*3+5-2, self.scrollView.frame.size.height/5*3+70, self.scrollView.frame.size.width/20*9, self.scrollView.frame.size.height/100*23);
    [self.buttonOne addTarget:self action:@selector(buttonOneClike:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:self.buttonOne];
    [self.buttonOne setImage:[UIImage imageNamed:@"hello.png"] forState:UIControlStateNormal];
    
    
    
    
    //***************************************//
    
   //最后四个button,two
    self.buttonTwo = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonTwo.frame = CGRectMake(self.scrollView.frame.size.width/2+5+4, self.scrollView.frame.size.height/5*3+70, self.scrollView.frame.size.width/20*9, self.scrollView.frame.size.height/100*23);
    [self.buttonTwo addTarget:self action:@selector(buttonTwoClike:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:self.buttonTwo];
    [self.buttonTwo setImage:[UIImage imageNamed:@"baby.png"] forState:UIControlStateNormal];



    
    //*************************************//
    
   //最后四个button,three
    self.buttonThree = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonThree.backgroundColor = [UIColor redColor];
    self.buttonThree.frame = CGRectMake(self.scrollView.frame.size.width/100*3+5-2, self.scrollView.frame.size.height/20*17+70, self.scrollView.frame.size.width/20*9, self.scrollView.frame.size.height/100*23);
    [self.buttonThree addTarget:self action:@selector(buttonThreeClike:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:self.buttonThree];
    [self.buttonThree setImage:[UIImage imageNamed:@"fan.png"] forState:UIControlStateNormal];
    
    


    
    //**************************************//
    
   //最后四个button,four
    self.buttonFour = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonFour.frame = CGRectMake(self.scrollView.frame.size.width/2+5+4, self.scrollView.frame.size.height/20*17+70, self.scrollView.frame.size.width/20*9, self.scrollView.frame.size.height/100*23);
    [self.buttonFour addTarget:self action:@selector(buttonFourClike:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:self.buttonFour];
    [self.buttonFour setImage:[UIImage imageNamed:@"tea.png"] forState:UIControlStateNormal];
    
    
    //***************************//
    //结束
    self.labelEnd = [[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.frame.size.width/5*2, self.scrollView.frame.size.height+self.scrollView.frame.size.height/11+15+60, self.scrollView.frame.size.width/100*21+10, self.scrollView.frame.size.height/500*11)];
    self.labelEnd.text = @"The End~";
    self.labelEnd.textColor = [UIColor lightGrayColor];
    self.labelEnd.textAlignment = 1;
    self.labelEnd.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:self.labelEnd];
    [_labelEnd release];
    
    
    
    self.labelCity.text = [NSString stringWithFormat:@"%@同城美食", self.cityString];
    

}

//buttonActionh活动的点击方法
- (void)buttonActionClike:(UIButton *)buttonAction
{

    
    
    
}
//更改城市BUtton的点击方法
- (void)buttonCityClike:(UIButton *)buttonCity
{
    ChangeCityViewController *changeCityVC = [[ChangeCityViewController alloc]init];
    [self.navigationController pushViewController:changeCityVC animated:YES];
    [changeCityVC release];
}

//附近店铺的点击方法
- (void)buttonShopClike:(UIButton *)buttonShop
{
//   
    
    CrossSlipViewController *crossVC = [[CrossSlipViewController alloc] init];
    crossVC.address = @"/v2/shop/near/?&gps=38.883987,121.540725";
    crossVC.activityOrNearShop = @"nearShop";
    [self.navigationController pushViewController:crossVC animated:YES];
    [crossVC release];

}
//同城热门的点击方法
- (void)buttonHotClike:(UIButton *)buttonHot
{
   // 设置自动定位功能 当选中某一个城市的时候自动获取该城市的经纬度 并用于传值请求该城市下得美食数据
    NSString *string = self.cityString;
    CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
    [myGeocoder geocodeAddressString:string completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0 && error == nil)
        {
            NSLog(@"Found %lu placemark(s).", (unsigned long)[placemarks count]);
            CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
            NSLog(@"Longitude = %f", firstPlacemark.location.coordinate.longitude);
            NSLog(@"Latitude = %f", firstPlacemark.location.coordinate.latitude);
            // 推出下一个界面
            self.food = [[Food alloc] init];
            // 拼接字符串 把经纬度拼接到网络地址中去
            self.food.objId = [NSString stringWithFormat:@"/v2/discover/hot/?&gps=%.6f, %.6f", firstPlacemark.location.coordinate.latitude, firstPlacemark.location.coordinate.longitude];
            // 推出“更多详情界面”
            MoreDetailViewController *moredetailVC = [[MoreDetailViewController alloc]init];
            moredetailVC.food = self.food;
            [self.navigationController pushViewController:moredetailVC animated:YES];
            [moredetailVC release];
            
        }
        else if ([placemarks count] == 0 && error == nil)
        {
            NSLog(@"Found no placemarks.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
        
    }];
    
}

//最后四个button,one的点击方法
- (void)buttonOneClike:(UIButton *)buttonOne
{
//    UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"1111你好么" message:@"11234567811111" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"很好",@"不好", nil];
//    
//    [aler show];
//    [aler release];

    
    FoodListDetailViewController *foodDetailshengdanVC = [[FoodListDetailViewController alloc] init];
    
     //将api参数传给详情页面
    foodDetailshengdanVC.address = @"/v2/slist/l_CLa9.UOqHZ";
    
    
    [self.navigationController pushViewController:foodDetailshengdanVC animated:YES];
    [foodDetailshengdanVC release];
    
    
    
    
    
}
//最后四个button,Two的点击方法
- (void)buttonTwoClike:(UIButton *)buttonTwo
{
//    UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"1111你好么" message:@"112345xcvbnm1111" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"很好",@"不好", nil];
//    
//    [aler show];
//    [aler release];
    FoodListDetailViewController *foodDeatilBabyVC = [[FoodListDetailViewController alloc]init];
    foodDeatilBabyVC.address = @"/v2/slist/l_CLa9.ROBdG";
    
    [self.navigationController pushViewController:foodDeatilBabyVC animated:YES];
    [foodDeatilBabyVC release];
    
    
    
}
//最后四个button,Three的点击方法
- (void)buttonThreeClike:(UIButton *)buttonThree
{
//    UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"1111你好么" message:@"你哈你你啊啊啊啊啊234567811111" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"很好",@"不好", nil];
//    
//    [aler show];
//    [aler release];
    FoodListDetailViewController *foodDeatilZhouVC = [[FoodListDetailViewController alloc]init];
    foodDeatilZhouVC.address = @"/v2/slist/l_CLa9A2aWuQ";
    [self.navigationController pushViewController:foodDeatilZhouVC animated:YES];
    [foodDeatilZhouVC release];
    

}
//最后四个button,Four的点击方法
- (void)buttonFourClike:(UIButton *)buttonFour
{
//    UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"1111你好么" message:@"112345受打击的萨拉科技路撒肯德基67811111" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"很好",@"不好", nil];
//    
//    [aler show];
//    [aler release];
    FoodListDetailViewController *foodDeatilTeaVC = [[FoodListDetailViewController alloc]init];
    foodDeatilTeaVC.address = @"/v2/slist/l_CLa9.MEBfr";
    [self.navigationController pushViewController:foodDeatilTeaVC animated:YES];
    [foodDeatilTeaVC release];

}

// 当收到通知中心消息的时候执行下面程序
- (void)receiveNotification:(NSNotification *)noti
{
    NSString *string = [NSString stringWithFormat:@"%@同城美食", noti.object];
    self.labelCity.text = string;
    self.cityString = noti.object;
    
}

// 当收到通知中心消息的时候改变省名的是偶执行下面的方法 
- (void)changeProvinceAction:(NSNotification *)noti
{
    NSString *string = [NSString stringWithFormat:@"%@同城美食", noti.object];
    self.labelCity.text = string;
    self.cityString = noti.object;
}

// 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
    if ([self GetCurrntNet]) {
        //[self handleData];
//        [self handleData];
        
    }
    else {
        /// 缓冲
        //        NSLog(@"没有网络");
        self.noHUD = [[MBProgressHUD alloc]initWithView:self.view];
        [self.noHUD setMode:MBProgressHUDModeIndeterminate];
        self.noHUD.labelText = @"网络不可用,请检查";
        [self.noHUD show:YES];
        [self performSelector:@selector(removeNoHUDView) withObject:self afterDelay:2];
        [self.view addSubview:_noHUD];
        [_noHUD release];
    }
//    [self.scrollView reloadData];
    
}

-(NSString*) GetCurrntNet
{
    NSString* result;
    Reachability *r = [Reachability reachabilityWithHostname:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:     // 没有网络连接
            result=nil;
            break;
        case ReachableViaWWAN: // 使用3G网络
            result=@"3g";
            break;
        case ReachableViaWiFi: // 使用WiFi网络
            result=@"wifi";
            break;
    }
    return result;
}

-(void)removeNoHUDView
{
    [self.noHUD removeFromSuperview];
}




- (void)dealloc
{
    [_scrollView release];
    
    [_buttonAction release];
    [_buttonCity release];
    [_buttonHot release];
    [_buttonOne release];
    [_buttonShop release];
    [_buttonTwo release];
    [_buttonThree release];
    [_buttonFour release];
    
    [_labelAction release];
    [_labelCity release];
    [_labelEnd release];
    [_labelNext release];
    
    [_arr release];
    [_cityString release];
    
    
    [super dealloc];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
